package com.company.project.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.company.project.common.constant.OSSEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.List;

/**
 * 阿里云oss 工具类
 *
 * @author Lenovo
 */
@Component
@Slf4j
public class AliOssUtils {

    private OSS ossClient;

    @Value("${oss.ak:}")
    private String ak;

    @Value("${oss.ck:}")
    private String ck;

    @Value("${oss.endpoint:}")
    private String endpoint;

    /**
     * 初始化oss
     */
    @PostConstruct
    private void init() {
        if (StringUtils.isNoneBlank(ak) && StringUtils.isNoneBlank(ck)) {
            ossClient = new OSSClientBuilder().build(endpoint, ak, ck);
            log.info("初始化阿里云OSS成功");
        }
    }


    /**
     *
     * 默认创建的是标准存储 ， 同城冗余存储 ，存储空间的权限为公共读
     * @param bucketName 这里创建默认权限 直传入一个桶名字，如果需要设置另外三个属性，传入CreateBucketRequest 对象
     */
    public void createBucket(String bucketName){
        try {
            ossClient.createBucket(bucketName);
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        log.info("阿里云创建新桶成功,桶名称{}" , bucketName);
    }

    /**
     * 查询桶列表
     * @return
     */
    public List<Bucket> getBucketList(){
        List<Bucket> buckets = ossClient.listBuckets();
        for (Bucket bucket : buckets) {
           log.info("查询到桶信息 - " + bucket.getName());
        }
        return buckets;
    }

    /**
     * 判断存储空间是否存在
     * @return boolean
     */
    public boolean exists(String bucket){
        // 判断存储空间examplebucket是否存在。如果返回值为true，则存储空间存在，否则存储空间不存在。
        boolean exists = ossClient.doesBucketExist(bucket);
        return exists;
    }

    /**
     * 上传图片
     *
     * @param ossEnum
     * @param key
     * @param is
     */
    public void upload(OSSEnum ossEnum, String key, InputStream is) {
//        if (ossEnum == OSSEnum.IMAGE) {
            ossClient.putBucketImage(new PutBucketImageRequest(ossEnum.getBucketName()));
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(ossEnum.getBucketName(), key, is));
            log.info("OSS UPLOAD REQUESID:[{}],ETAGS", result.getRequestId(), result.getETag());
//        }
    }

    /**
     * 获取某个存储空间下指定目录（文件夹）下的文件大小。
     * @param bucketName 桶名
     * @param folder 文件夹
     * @return 返回单位是 b 需要自己转换成kb 或者Gb
     *
     */
    public long calculateFolderLength(String bucketName, String folder) {
        long size = 0L;
        ListObjectsV2Result result = null;
        do {
            // MaxKey默认值为100，最大值为1000。
            ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withPrefix(folder).withMaxKeys(1000);
            if (result != null) {
                request.setContinuationToken(result.getNextContinuationToken());
            }
            result = ossClient.listObjectsV2(request);
            List<OSSObjectSummary> sums = result.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                size += s.getSize();
            }
        } while (result.isTruncated());
        return size;
    }


}
